package com.example.littlepainter.draw

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.littlepainter.data.PictureViewModel
import com.example.littlepainter.databinding.FragmentDrawBinding
import com.example.littlepainter.db.Picture
import com.example.littlepainter.draw.color.ColorAdapter
import com.example.littlepainter.utils.ColorUtils
import com.example.littlepainter.utils.FileUtils
import com.example.littlepainter.utils.TimeUtils
import com.example.littlepainter.utils.convertViewToBitmap
import com.example.littlepainter.utils.scaleBitmap
import kotlinx.coroutines.launch


class DrawFragment : Fragment() {
    private lateinit var binding:FragmentDrawBinding
    private val mViewModel:DrawViewModel by viewModels()
    private val mAdapter = ColorAdapter()
    private val args:DrawFragmentArgs by navArgs()
    private val mPictureViewModel:PictureViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentDrawBinding.inflate(inflater,container,false)
        return binding.root
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.drawView.apply {
            viewModel = mViewModel
            lifeCycleOwner = viewLifecycleOwner
            args.currentPicture?.let {
                lifecycleScope.launch {
                    backgroundBitmap = FileUtils().loadBitmapFromPath(it.url)
                }
            }
        }
        args.currentPicture?.let {
            binding.nameEditText.setText(it.name)
        }
        binding.toolContainer.viewModel = mViewModel
        binding.progressView.mDrawViewModel = mViewModel

        //配置colorRecyclerView
        binding.colorRecyclerView.apply {
            layoutManager = LinearLayoutManager(context,RecyclerView.HORIZONTAL,false)
            adapter = mAdapter
        }

        //让adapter持有viewModel对象
        mAdapter.mDrawViewModel = mViewModel

        //监听颜色模型类对象
        mViewModel.mColorModels.observe(viewLifecycleOwner){
            //有数据了 数据变化了
            mAdapter.setData(it)
        }

        binding.backBtn.setOnClickListener {
            //新作品
            if (args.currentPicture == null  && !binding.drawView.isEmpty() ){
                lifecycleScope.launch {
                    //将drawView -> Bitmap
                    val bitmap = convertViewToBitmap(binding.drawView)
                    //获取当前时间
                    val time = TimeUtils.time()
                    //获取名字
                    val name = binding.nameEditText.text.trim().toString()
                    //缩略图
                    val thumbnail = scaleBitmap(bitmap,0.5f)
                    //将原图保存到文件中
                    val url =  FileUtils().saveBitmap(bitmap)
                    //保存
                    mPictureViewModel.savePicture(
                        Picture(0,name,time, url,thumbnail)
                    )
                }

            }
           args.currentPicture?.let {
               var shouldUpdate = false
               if (!binding.drawView.isEmpty()){//画了新东西
                   lifecycleScope.launch {
                       val bitmap = convertViewToBitmap(binding.drawView)
                       //缩略图
                       val thumbnail = scaleBitmap(bitmap,0.5f)
                       //将原图保存到文件中
                       val path =  FileUtils().saveBitmap(bitmap)
                       //删除之前的图片
                       FileUtils().deleteFile(it.url)
                       //保存新的url
                       it.url = path
                       it.thumbnail = thumbnail

                       shouldUpdate = true
                   }
               }
               if(it.name != binding.nameEditText.text.toString()){
                   it.name = binding.nameEditText.text.toString()
                   shouldUpdate = true
               }

               if (shouldUpdate){
                   mPictureViewModel.updatePicture(it)
               }
           }
            findNavController().navigateUp()
        }
    }

}












